package com.topnav.mc.admin.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.js.lib.utils.JsonUtil;
import com.topnav.mc.admin.dao.mapper.GbQuartzMapper;
import com.topnav.mc.admin.entity.GbQuartzJob;
import com.topnav.mc.admin.entity.bean.GbQuartzJobBean;
import com.topnav.mc.admin.entity.param.GbQuartzJobParam;
import com.topnav.mc.admin.service.IGbQuartzService;
import com.topnav.mc.schedule.JobManagement;
import com.topnav.mc.schedule.task.QuartzTask;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.topnav.mc.base.mc.McServiceImpl;
import java.util.HashMap;
import java.util.Map;

@Service
public class GbQuartzJobServiceImpl extends McServiceImpl<
        GbQuartzMapper, GbQuartzJob, GbQuartzJobBean, GbQuartzJobParam> implements IGbQuartzService {

    @Autowired
    private JobManagement jobManagement;

    /**
     * 根据 ID 选择修改
     *
     * @param entity 实体对象
     */
    @Override
    public boolean updateById(GbQuartzJob entity) {
        if (!beforeUpdate(entity)){return false;}

        if ("subscribePostionJob".equals(entity.getJobName())){
            /** 位置订阅要带参数 */
            String[] s1 = entity.getCron().split(" ");
            /** 订阅过期时间 秒*/
            String[] s2 = s1[1].split("/");
            String s3 =  s2.length>1?s2[1]:s2[0];

            Integer expires = Integer.valueOf(s3.toString()) * 60;
            /** 订阅频率 秒*/
            Integer interval = 30;
            Map<String,Object> jobDataMap = new HashMap<>();
            jobDataMap.put("expires",expires);
            jobDataMap.put("interval",interval);
            entity.setParams(JsonUtil.toJson(jobDataMap));
        }

        boolean result = super.updateById(entity);
        //boolean result = SqlHelper.retBool(getBaseMapper().updateById(entity));
        if (result){afterUpdate(entity);}

        /** 原 gbQuartzJob */
        GbQuartzJob gbQuartzJob = this.getById(entity.getId());

        /** 停止再重新启动 */
        QuartzTask task = gbQuartzJob.toTask();
        jobManagement.stopTask(task);
        jobManagement.removeTask(task);

        if (gbQuartzJob.getStatus() == 1){
            jobManagement.addJob(task);
        }
        try {
            jobManagement.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return result;
    }
}
